/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.codeminer.parts.server.actions;

import org.codeminer.database.DatabaseException;
import org.codeminer.database.DatabaseManager;
import org.codeminer.parts.constants.MessageConstants;
import org.codeminer.parts.database.PlaylistConnector;
import org.codeminer.parts.library.Playlist;
import org.codeminer.parts.server.permissions.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.EnumSet;
import java.util.List;
import java.util.Set;

public class GetAllPlaylists implements Action {

    private static final Logger log = LoggerFactory.getLogger(GetAllPlaylists.class);
    private final String VERSION = "2";
    private ActionContext context;
    private final Set<Permission> permissions = EnumSet.noneOf(Permission.class);

    public GetAllPlaylists(ActionContext context) {
        this.context = context;
        this.permissions.add(Permission.READ_PLAYLISTS);
    }

    @Override
    public String getVersion() {
        return this.VERSION;
    }

    @Override
    public Set<Permission> requiredPermissions() {
        return this.permissions;
    }

    @Override
    public Response execute() {
        try {
            final PlaylistConnector playlistConnector = context.getApplicationPart(DatabaseManager.class).getConnector(PlaylistConnector.class);
            return createOK(playlistConnector.getPlaylists(context.getCurrentSessionUser()));
        } catch (DatabaseException ex) {
            log.debug("could not get playlists", ex);
            return createError(MessageConstants.ACTION_DEFAULT_ERROR, "could not get playlists");
        }

    }

    private Response createOK(List<Playlist> playlists) {
        Response response = new Response("OK");
        response.addProperty("playlists", playlists);
        return response;
    }

    private Response createError(String messageKey, String message) {
        Response response = new Response("Error");
        response.addProperty("message.key", messageKey);
        response.addProperty("message", message);
        return response;
    }
}
